#!/bin/bash

# 默认参数
BUILD_TYPE="native"
CROSS_HOST=""
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
MQTT_C_DIR="$SCRIPT_DIR/MQTT-C"
COM_LIB_DIR="$SCRIPT_DIR/com_lib"
COM_INC_DIR="$SCRIPT_DIR/com_inc"
EASY_LOGGER_DIR="$SCRIPT_DIR/EasyLogger"
LW_LOG_DIR="$SCRIPT_DIR/../lw_log"

# 默认启用MQTT
ENABLE_MQTT="y"

show_help() {
    cat << EOF
Usage: $0 [OPTIONS]

Options:
    --cross-compile         Enable cross compilation
    --host HOST             Set host for cross compilation (e.g., arm-linux-gnueabihf)
    --disable-mqtt          Disable MQTT support
    --help                  Show this help message

Examples:
    # Native compilation
    ./build.sh

    # Cross compilation for ARM
    ./build.sh --cross-compile --host arm-linux-gnueabihf
    
    # Native compilation without MQTT
    ./build.sh --disable-mqtt
EOF
}

# 解析参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --cross-compile)
            BUILD_TYPE="cross"
            shift
            ;;
        --host)
            CROSS_HOST="$2"
            shift 2
            ;;
        --disable-mqtt)
            ENABLE_MQTT="n"
            shift
            ;;
        --help)
            show_help
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# 创建必要的目录
mkdir -p "$COM_LIB_DIR"
mkdir -p "$COM_INC_DIR"

# 构建MQTT库（如果启用）
build_mqtt() {
    # 如果禁用MQTT，直接退出
    if [ "$ENABLE_MQTT" = "n" ]; then
        echo "MQTT support disabled. Skipping MQTT build."
        return 0
    fi

    # clone 仓库
    if [ ! -d "$MQTT_C_DIR" ]; then
        echo "Cloning MQTT-C repository to $MQTT_C_DIR..."
        git clone https://github.com/LiamBindle/MQTT-C.git "$MQTT_C_DIR"
        if [ $? -ne 0 ]; then
            echo "Error: git clone failed!"
            exit 1
        fi
    else
        echo "MQTT-C 已存在于 $MQTT_C_DIR，跳过 clone。"
    fi

    cd "$MQTT_C_DIR"

    # 选择编译器
    if [ "$BUILD_TYPE" = "cross" ]; then
        if [ -z "$CROSS_HOST" ]; then
            echo "Error: --host is required for cross-compilation"
            exit 1
        fi
        COMPILER="${CROSS_HOST}-gcc"
        if ! command -v ${COMPILER} &> /dev/null; then
            echo "Error: Cross-compiler ${COMPILER} not found!"
            exit 2
        fi
    else
        COMPILER="gcc"
    fi

    # 生成 Makefile.custom
    cat > Makefile.custom << EOF
CC = ${COMPILER}
CFLAGS = -Wextra -Wall -std=gnu99 -fPIC -Iinclude -Wno-unused-parameter -Wno-unused-variable -Wno-duplicate-decl-specifier

SRCDIR = src
INCLUDEDIR = include
SOURCES = mqtt.c mqtt_pal.c
OBJECTS = src/mqtt.o src/mqtt_pal.o
VPATH = src

all: libmqttc.so

src/%.o: %.c
	\$(CC) \$(CFLAGS) -c \$< -o \$@

libmqttc.so: \$(OBJECTS)
	\$(CC) -shared -o \$@ \$^ -lpthread

clean:
	rm -f \$(OBJECTS) libmqttc.so

install: libmqttc.so
	mkdir -p ${COM_LIB_DIR}
	mkdir -p ${COM_INC_DIR}
	cp libmqttc.so ${COM_LIB_DIR}/
	cp -r \$(INCLUDEDIR)/* ${COM_INC_DIR}/

.PHONY: all clean install
EOF

    # 编译和安装
    make -f Makefile.custom clean
    if make -f Makefile.custom all; then
        echo "编译成功，正在安装到 ${COM_LIB_DIR} 和 ${COM_INC_DIR}..."
        make -f Makefile.custom install
        echo "MQTT-C build completed successfully!"
        echo "动态库已复制到: ${COM_LIB_DIR}"
        echo "头文件已复制到: ${COM_INC_DIR}"
    else
        echo "MQTT-C 编译失败！"
        exit 3
    fi

    cd "$SCRIPT_DIR"
}

# 构建日志库
build_log() {
    echo "Building log library..."
    
    # 检查EasyLogger是否存在
    if [ ! -d "$EASY_LOGGER_DIR" ]; then
        echo "Error: EasyLogger directory not found at $EASY_LOGGER_DIR"
        exit 4
    fi
    
    # 选择编译器
    if [ "$BUILD_TYPE" = "cross" ]; then
        if [ -z "$CROSS_HOST" ]; then
            echo "Error: --host is required for cross-compilation"
            exit 1
        fi
        COMPILER="${CROSS_HOST}-gcc"
        if ! command -v ${COMPILER} &> /dev/null; then
            echo "Error: Cross-compiler ${COMPILER} not found!"
            exit 2
        fi
    else
        COMPILER="gcc"
    fi
    
    # 编译EasyLogger源文件
    EASY_LOGGER_SOURCES=(
        "$EASY_LOGGER_DIR/easylogger/src/elog.c"
        "$EASY_LOGGER_DIR/easylogger/src/elog_async.c"
        "$EASY_LOGGER_DIR/easylogger/src/elog_buf.c"
        "$EASY_LOGGER_DIR/easylogger/src/elog_utils.c"
        "$EASY_LOGGER_DIR/easylogger/port/elog_port.c"
    )
    
    EASY_LOGGER_OBJECTS=()
    COMPILE_FLAGS="-Wextra -Wall -std=gnu99 -fPIC -I$EASY_LOGGER_DIR/easylogger/inc -I$EASY_LOGGER_DIR/easylogger/port"
    
    # 编译每个源文件
    for src in "${EASY_LOGGER_SOURCES[@]}"; do
        obj="${src%.c}.o"
        EASY_LOGGER_OBJECTS+=("$obj")
        
        echo "Compiling $src..."
        $COMPILER $COMPILE_FLAGS -c "$src" -o "$obj"
        if [ $? -ne 0 ]; then
            echo "Error: Failed to compile $src"
            exit 5
        fi
    done
    
    # 创建libelog.a静态库
    echo "Creating libelog.a..."
    ar rcs "$COM_LIB_DIR/libelog.a" "${EASY_LOGGER_OBJECTS[@]}"
    if [ $? -ne 0 ]; then
        echo "Error: Failed to create libelog.a"
        exit 6
    fi
    
    # 复制头文件
    echo "Copying header files..."
    cp -r "$EASY_LOGGER_DIR/easylogger/inc/"* "$COM_INC_DIR/"
    
    echo "Log library build completed successfully!"
}

# 构建lw_log库
build_lw_log() {
    echo "Building lw_log library..."
    
    # 检查lw_log是否存在
    if [ ! -d "$LW_LOG_DIR" ]; then
        echo "Error: lw_log directory not found at $LW_LOG_DIR"
        exit 7
    fi
    
    # 选择编译器
    if [ "$BUILD_TYPE" = "cross" ]; then
        if [ -z "$CROSS_HOST" ]; then
            echo "Error: --host is required for cross-compilation"
            exit 1
        fi
        COMPILER="${CROSS_HOST}-gcc"
        if ! command -v ${COMPILER} &> /dev/null; then
            echo "Error: Cross-compiler ${COMPILER} not found!"
            exit 2
        fi
    else
        COMPILER="gcc"
    fi
    
    LW_LOG_SOURCE="$LW_LOG_DIR/lw_log.c"
    LW_LOG_OBJECT="$LW_LOG_DIR/lw_log.o"
    
    COMPILE_FLAGS="-Wextra -Wall -std=gnu99 -fPIC -I$COM_INC_DIR -I$LW_LOG_DIR"
    
    echo "Compiling $LW_LOG_SOURCE..."
    $COMPILER $COMPILE_FLAGS -c "$LW_LOG_SOURCE" -o "$LW_LOG_OBJECT"
    if [ $? -ne 0 ]; then
        echo "Error: Failed to compile $LW_LOG_SOURCE"
        exit 8
    fi
    
    # 创建liblw_log.so动态库
    echo "Creating liblw_log.so..."
    $COMPILER -shared -fPIC -o "$COM_LIB_DIR/liblw_log.so" "$LW_LOG_OBJECT" -lpthread
    if [ $? -ne 0 ]; then
        echo "Error: Failed to create liblw_log.so"
        exit 9
    fi
    
    # 复制头文件
    echo "Copying lw_log header files..."
    cp "$LW_LOG_DIR/lw_log.h" "$COM_INC_DIR/"
    
    echo "lw_log library build completed successfully!"
}

# 主构建流程
main() {
    echo "Starting build process..."
    
    # 构建MQTT库
    build_mqtt
    
    # 构建日志库
    build_log
    
    # 构建lw_log库
    build_lw_log
    
    echo "All libraries built successfully!"
}

# 执行主构建流程
main